package com.knife.blog.web.action;


import com.knife.blog.domain.BlogInfo;
import com.knife.blog.logic.BlogUserService;
import com.knife.blog.logic.CurrentUser;
import com.knife.blog.logic.SysConfig;
import com.knife.blog.logic.impl.BlogCircleDirServiceImpl;
import com.knife.blog.logic.impl.BlogCoreServiceImpl;
import com.knife.blog.logic.impl.BlogMessageServiceImpl;
import com.knife.blog.logic.impl.BlogReviewServiceImpl;
import com.knife.blog.logic.impl.BlogUserServiceImpl;
import com.knife.blog.logic.impl.PhotoServiceImpl;
import com.knife.web.ActionContext;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.tools.CrudAction;
import com.knife.web.tools.IActiveUser;

abstract class BaseCrudAction extends CrudAction {

    protected BlogInfo blog;
    protected BlogUserService userService = BlogUserServiceImpl.getInstance();

    @Override
    public IActiveUser getCurrentUser(WebForm form) {
        // return (IActiveUser) ActionContext.getContext().getSession()
        // .getAttribute("user");
        return com.knife.blog.logic.CurrentUser.getActiveUser();
    }

    @Override
    public Object doBefore(WebForm form, Module module) {
        IActiveUser user = CurrentUser.getActiveUser();
        if (user == null) {
            // 请先登录
            String url="/manage.do";
            form.addResult("msg", "请先登录！");
            form.addResult("js", "top.location.href='"+url+"';");
            return new Page("index", "/manage/javascript.html", "template");
            //return module.findPage("login");
        }
        blog = userService.getUserBlog(user.getUserName());
        if (blog == null) {
            form.addResult("msg", "你还没申请Blog服务，请先申请开通Blog服务！");
            form.addResult("username", user.getUserName());
            return module.findPage("register");
        }
        return super.doBefore(form, module);

    }
    
    @Override
    public void doAfter(WebForm form, Module module) {
        SysConfig sysConfig = (SysConfig) ActionContext.getContext().getSession().getServletContext().getAttribute("sysConfig");
        form.addResult("sysConfig", sysConfig);
        form.addResult("dirService", BlogCoreServiceImpl.getInstance());
        form.addResult("cocService", BlogCoreServiceImpl.getInstance());
        form.addResult("currentUser", CurrentUser.getActiveUser());
        form.addResult("photoService", PhotoServiceImpl.getInstance());
        form.addResult("reviewService", BlogReviewServiceImpl.getInstance());
        form.addResult("messageService", BlogMessageServiceImpl.getInstance());
        form.addResult("circleDirService", BlogCircleDirServiceImpl.getInstance());
        if (blog != null) {
            form.addResult("blog", blog);
            form.addResult("templateName", blog.getTemplate());
        }
        super.doAfter(form, module);
    }
}
